package com.bdy.translate.util;

import android.util.Log;

import com.bdy.translate.listener.AnotherResultListener;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sy.lib_secretkey.BaseCallBackListener;
import com.sy.lib_secretkey.SecretkeyUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class BdyPhotoTranslateTool {
    private String appKey;
    private String secretKey;
    private AnotherResultListener resultListener;
    private String access_token;
    //获取token的地址
    private String TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";
    //文本翻译的地址
    private String TRANSLATE_URL = "https://aip.baidubce.com/file/2.0/mt/pictrans/v1";

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    public void initbdyKey(String defaultSecretKey, String keyName) {
        SecretkeyUtils.getSecretkey(defaultSecretKey, keyName, new BaseCallBackListener<String>() {
            @Override
            public void onSuccess(String s) {

                String[] res = SecretkeyUtils.formatKey(s);
                LogUtils.e("key:"+ Arrays.toString(res));
                appKey = res[0];
                secretKey = res[1];
                getToken();
            }

            @Override
            public void onFailed(String s) {
                System.out.println("onFailed========" + s);
            }

            @Override
            public void onHandlerStart() {
                System.out.println("onHandlerStart========");
            }
        });
    }

    private void getToken() {
        //第一步，先获取token
        String url = TOKEN_URL + "?grant_type=client_credentials&client_id=" + appKey + "&client_secret=" + secretKey;
        requst(url, 1, "", "", null);
    }

    public void transLateToOtherLanguage(String from, String to, File file, AnotherResultListener resultListener) {
        this.resultListener = resultListener;
        if (file.length() > 3145728) {
            ToastUtils.showShort("选择的图片不能大于4M");
            return;
        }

        Log.d("aaaa1",TRANSLATE_URL);
        Log.d("aaaa2",access_token+"1111");
        Log.d("aaaa3",from);
        Log.d("aaaa4",to);
        Log.d("aaaa5",file.toString());

        requst(TRANSLATE_URL + "?access_token=" + access_token, 2, from, to, file);
    }

    //发送请求的地址和数据
    private void requst(String url, final int position, String from, String to, File file) {
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        Request request = null;
        if (position == 1) {
            request = new Request.Builder()
                    .url(url)
                    .get()
                    .build();
        } else if (position == 2) {
            MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
            multipartBodyBuilder.setType(MultipartBody.FORM);
            multipartBodyBuilder.addFormDataPart("from", from);
            multipartBodyBuilder.addFormDataPart("to", to);
            multipartBodyBuilder.addFormDataPart("v", "3");
            multipartBodyBuilder.addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE_PNG, file));
            mediaType = MediaType.parse("multipart/form-data");
            request = new Request.Builder()
                    .url(url)
                    .addHeader("access_token", access_token)
                    .post(multipartBodyBuilder.build())
                    .build();
        }

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onResponse========" + e.getMessage());
                resultListener.Failed("翻译失败!");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String res = response.body().string();
                System.out.println("onResponse========" + res);
                if (position == 1) {
                    if (res == null || res.isEmpty()) {
                        resultListener.Failed("翻译失败!");
                        return;
                    }
                    try {
                        JSONObject jsonObject = new JSONObject(res);
                        access_token = jsonObject.getString("access_token");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else if (position == 2) {
                    System.out.println("res======" + res);
                    if (res == null || res.isEmpty()) {
                        resultListener.Failed("翻译失败!");
                        return;
                    }
                    try {
                        JSONObject jsonObject1 = new JSONObject(res);
                        int error_code = jsonObject1.getInt("error_code");
                        if (error_code == 0) {
                            String sumSrc = jsonObject1.getJSONObject("data").getString("sumSrc");
                            String sumDst = jsonObject1.getJSONObject("data").getString("sumDst");
                            resultListener.Success(sumSrc, sumDst);
                        } else {
                            resultListener.Failed("翻译失败!");
                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


}
